package com.supcalls.tool;

import java.util.concurrent.*;

/**
 * Phaser 是一个比 CountDownLatch 更灵活的同步工具，允许动态的线程数量和阶段控制。
 */
public class PhaserDemo {
    public static void main(String[] args) throws InterruptedException {
        Phaser phaser = new Phaser(1);  // Initial phase, main thread is registered

        for (int i = 0; i < 3; i++) {
            final int taskId = i;
            new Thread(() -> {
                System.out.println("Task " + taskId + " is starting.");
                phaser.arriveAndAwaitAdvance();  // Wait for the other threads to arrive at the barrier
                System.out.println("Task " + taskId + " is doing its work.");
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                phaser.arriveAndAwaitAdvance();  // Wait for all threads to complete
                System.out.println("Task " + taskId + " is finished.");
            }).start();
        }

        // Register the main thread and start the phases
        phaser.arriveAndAwaitAdvance();  // Wait for all threads to start their tasks
        phaser.arriveAndDeregister();  // Deregister the main thread when done
    }
}
